package de.herberlin.pss;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

import de.herberlin.pss.ui.Frame;

import SQLite.Exception;

public class ServiceCallback implements SQLite.Callback {

	private Logger logger = Logger.getLogger(getClass());
	private String[] coldata = null;
	private List<Properties> result = new LinkedList<Properties>();

	private String filename = null;

	public ServiceCallback(String filename) {
		this.filename = filename;
	}

	public void columns(String[] coldata) {
		this.coldata = coldata;

	}

	public boolean newrow(String[] rowdata) {

		if (rowdata == null) {
			logger.warn("Row-data must not be null!");
			return false;
		}
		if (coldata == null) {
			logger.warn("Col-data must not be null!");
			return true;
		}

		if (rowdata.length != coldata.length) {
			logger.error("Length of rowdata and coldata must be the same!");
			return false;
		}

		Properties props = new Properties();
		for (int i = 0; i < coldata.length; i++) {
			if (rowdata[i] == null)
				continue;
			logger.debug(coldata[i] + "->" + rowdata[i]);
			props.setProperty(coldata[i], rowdata[i]);
			logger.debug("Props=" + props);
		}

		result.add(props);
		return false;
	}

	public List<Properties> getResult(String query) throws Exception {
		logger.info(query);
		SQLite.Database db = new SQLite.Database();
		try {
			db.open(filename, 1);
			db.exec(query, this);
		} catch (Exception e) {
			logger.error(e,e);
			Frame.showMessage(e.getLocalizedMessage(), e);
		} finally {
			if (db != null)
				db.close();
		}
		return result;
	}
	
	public Properties getFirstResult(String query) throws Exception {
		logger.info(query);
		List<Properties> result=getResult(query);
		if (result==null || result.size()<1) {
			return null;
		} else {
			return result.get(0);
		}
	}

	public void types(String[] types) {

	}

}
